<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="user" labelWidth="80px">
        <uni-forms-item label="用户昵称" name="nickName">
          <uni-easyinput v-model="user.nickName" placeholder="请输入昵称" />
        </uni-forms-item>
        <uni-forms-item label="手机号码" name="phonenumber">
          <uni-easyinput v-model="user.phonenumber" placeholder="请输入手机号码" />
        </uni-forms-item>
        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
        </uni-forms-item>
        <uni-forms-item label="性别" name="sex" required>
          <uni-data-checkbox v-model="user.sex" :localdata="sexs" />
        </uni-forms-item>
        <!-- 微信绑定项 -->
        <uni-forms-item label="微信绑定">
          <view class="wechat-binding">
            <text>{{ user.bound ? '已绑定 ': '未绑定' }}</text>
            <button 
              :type="user.bound ? 'default' : 'primary'" 
              size="mini" 
              class="wechat-btn"
              @click="handleWechatBinding"
              :loading="wechatLoading"
            >
              {{ user.bound ? '解除绑定' : '绑定微信' }}
            </button>
          </view>
        </uni-forms-item>
      </uni-forms>
      <button type="primary" @click="submit" class="submit-btn" :loading="submitLoading">提交</button>
    </view>
  </view>
</template>

<script>
import { getUserProfile } from "@/api/system/user"
import { updateUserProfile } from "@/api/system/user"
// 微信绑定相关API
import { bindWechat, unbindWechat, getWechatBindStatus } from "@/api/system/user"

export default {
  data() {
    return {
      user: {
        nickName: "",
        phonenumber: "",
        email: "",
        sex: "",
        bound: "" // 微信绑定字段，存储微信昵称
      },
      sexs: [
        { text: '男', value: "0" },
        { text: '女', value: "1" }
      ],
      rules: {
        nickName: {
          rules: [{
            required: true,
            errorMessage: '用户昵称不能为空'
          }]
        },
        phonenumber: {
          rules: [{
            required: true,
            errorMessage: '手机号码不能为空'
          }, {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            errorMessage: '请输入正确的手机号码'
          }]
        },
        email: {
          rules: [{
            required: true,
            errorMessage: '邮箱地址不能为空'
          }, {
            format: 'email',
            errorMessage: '请输入正确的邮箱地址'
          }]
        }
      },
      wechatLoading: false, // 微信操作加载状态
      submitLoading: false  // 提交按钮加载状态
    }
  },
  onLoad() {
    this.getUser()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    /**
     * 获取用户基本信息
     */
    getUser() {
      getUserProfile().then(response => {
        this.user = { ...response.data, bound: '' } // 初始化微信字段
        this.getWechatStatus() // 获取微信绑定状态
      }).catch(err => {
        this.$modal.msgError('获取用户信息失败：' + (err.message || '未知错误'))
      })
    },

    /**
     * 获取微信绑定状态
     */
    getWechatStatus() {
      getWechatBindStatus().then(response => {
		   console.log(response)
          this.user.bound = response.data.bound
		  console.log(this.user.bound)
      }).catch(err => {
        console.warn('获取微信绑定状态失败：', err)
        // 非关键错误，不阻断用户操作
      })
    },

    /**
     * 提交表单
     */
    submit() {
      this.submitLoading = true
      this.$refs.form.validate().then(res => {
        updateUserProfile(this.user).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.submitLoading = false
        }).catch(err => {
          this.$modal.msgError('修改失败：' + (err.message || '未知错误'))
          this.submitLoading = false
        })
      }).catch(err => {
        // 表单验证失败
        this.submitLoading = false
      })
    },

    /**
     * 处理微信绑定/解绑逻辑
     */
   async handleWechatBinding() {
		const loginResArr = await uni.login()
		const code =loginResArr[1].code
		console.log(loginResArr)
		console.log(code)
      if (this.user.bound) {
        // 解除绑定
        this.$modal.confirm('确定要解除微信绑定吗？')
          .then(() => {
            this.wechatLoading = true
            unbindWechat().then(response => {
              this.wechatLoading = false
              if (response.success) {
                this.$modal.msgSuccess('解除绑定成功')
                this.user.bound = ''
              } else {
                this.$modal.msgError(response.message || '解除绑定失败')
              }
            }).catch(err => {
              this.wechatLoading = false
              this.$modal.msgError('解除绑定失败：' + (err.message || '未知错误'))
            })
          })
          .catch(() => {
            // 用户取消操作
          })
      } else {
        // 绑定微信：先获取微信授权code
        this.wechatLoading = true
        if(code) {
          // 调用绑定接口
          bindWechat(code).then(response => {
            this.wechatLoading = false
            if (response.success) {
              this.$modal.msgSuccess('微信绑定成功')
              this.user.bound = response.data.nickname || '微信用户'
            } else {
              this.$modal.msgError(response.message || '微信绑定失败')
            }
          }).catch(err => {
            this.wechatLoading = false
            this.$modal.msgError('绑定失败：' + (err.message || '授权过程出错'))
          })
        }else {
          this.wechatLoading = false
          this.$modal.msgError('获取微信授权失败：' + (err.message || '无法获取授权码'))
        }
      }
    },

  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}

// 微信绑定样式
.wechat-binding {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.wechat-btn {
  min-width: 100px;
}

.submit-btn {
  margin-top: 20px;
  width: 100%;
}
</style>
